/**
 * 基础控制器类
 * 提供通用的数据库操作方法和响应格式化
 */

import database from '../../utils/database'
import { generateId } from '../../mock/utils'

// 确保数据库已初始化
let dbInitialized = false

export async function ensureDbInit() {
  if (!dbInitialized) {
    await database.init()
    dbInitialized = true
  }
}

// 统一响应格式包装器
export function createResponse(data: any = null, message: string = 'success', code: number = 0) {
  return {
    code,
    message,
    data
  }
}

// 统一错误响应
export function createErrorResponse(message: string, code: number = 1004) {
  return {
    code,
    message,
    data: null
  }
}

// 统一分页响应格式
export function createPaginationResponse(list: any[], page: number, pageSize: number, total: number) {
  // 确保所有参数都有合理的默认值，避免 undefined 或 NaN
  const safeList = Array.isArray(list) ? list : []
  const safePage = parseInt(String(page)) || 1
  const safePageSize = parseInt(String(pageSize)) || 20
  const safeTotal = parseInt(String(total)) || 0
  
  return createResponse({
    list: safeList,
    page: safePage,
    pageSize: safePageSize,
    total: safeTotal
  })
}

/**
 * 基础控制器类
 */
export abstract class BaseController {
  protected tableName: string
  
  constructor(tableName: string) {
    this.tableName = tableName
  }
  
  /**
   * 获取列表（分页）
   */
  protected async getList(params: {
    page?: number
    pageSize?: number
    where?: string
    whereParams?: any[]
    orderBy?: string
  }) {
    try {
      await ensureDbInit()
      const {
        page = 1,
        pageSize = 20,
        where = '1=1',
        whereParams = [],
        orderBy = 'created_at DESC'
      } = params || {}
      
      const result = await database.paginate(this.tableName, {
        page,
        pageSize,
        where,
        whereParams,
        orderBy
      })
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取列表失败')
      }
      
      const paginationData = result.data || {}
      return createPaginationResponse(
        paginationData.list,
        paginationData.page,
        paginationData.pageSize,
        paginationData.total
      )
    } catch (error: any) {
      return createErrorResponse(error.message || '获取列表失败')
    }
  }
  
  /**
   * 根据ID获取详情
   */
  protected async getDetail(id: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        `SELECT * FROM ${this.tableName} WHERE id = ? AND is_deleted = 0`,
        [id]
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '查询详情失败')
      }
      
      const records = result.data || []
      if (records.length === 0) {
        return createErrorResponse('记录不存在', 1003)
      }
      
      return createResponse(records[0])
    } catch (error: any) {
      return createErrorResponse(error.message || '获取详情失败')
    }
  }
  
  /**
   * 创建记录
   */
  protected async create(data: any) {
    try {
      await ensureDbInit()
      const id = generateId()
      const now = new Date().toISOString()
      
      const recordData = {
        id,
        ...data,
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert(this.tableName, recordData)
      
      return createResponse({
        id,
        ...data,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建记录失败')
    }
  }
  
  /**
   * 更新记录
   */
  protected async update(id: string, data: any) {
    try {
      await ensureDbInit()
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }
      
      const rowsAffected = await database.update(
        this.tableName,
        updateData,
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('记录不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新记录失败')
    }
  }
  
  /**
   * 删除记录（软删除）
   */
  protected async delete(id: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.update(
        this.tableName,
        { is_deleted: 1, updated_at: new Date().toISOString() },
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('记录不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除记录失败')
    }
  }
  
  /**
   * 物理删除记录
   */
  protected async hardDelete(id: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.delete(this.tableName, 'id = ?', [id])
      
      if (rowsAffected === 0) {
        return createErrorResponse('记录不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除记录失败')
    }
  }
  
  /**
   * 获取统计数据
   */
  protected async getCount(where: string = '1=1', whereParams: any[] = []) {
    try {
      await ensureDbInit()
      const result = await database.query(
        `SELECT COUNT(*) as count FROM ${this.tableName} WHERE ${where}`,
        whereParams
      )
      
      if (result.code !== 0) {
        return 0
      }
      
      const data = result.data || []
      return (data[0] && typeof data[0].count !== 'undefined') ? data[0].count : 0
    } catch (error) {
      return 0
    }
  }
}